package com.ruoyi.oto.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.MemberUser;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.oto.constants.DeleteFlag;
import com.ruoyi.oto.constants.MemberRoleConstant;
import com.ruoyi.oto.domain.*;
import com.ruoyi.oto.domain.dto.ReplaceUserDTO;
import com.ruoyi.oto.domain.dto.SetBranchUserDTO;
import com.ruoyi.oto.domain.dto.SetUserDTO;
import com.ruoyi.oto.domain.vo.MemberInfoVO;
import com.ruoyi.oto.service.BranchMemberService;
import com.ruoyi.oto.service.CompanyCoreService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.oto.mapper.MemberUserMapper;
import com.ruoyi.oto.service.MemberUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 会员服务
 *
 * @author ruoyi
 */
@Service
public class MemberUserServiceImpl extends ServiceImpl<MemberUserMapper, MemberUser> implements MemberUserService
{
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private BranchMemberService branchMemberService;
    @Autowired
    private CompanyCoreService companyCoreService;
    /**
     * 根据openID获取登录用户信息
     * @param openid
     * @return
     */
    @Override
    public MemberUser getByOpendid(String openid) {
        return this.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getOpenId,openid));
    }

    /**
     * 获取会员信息
     * @param member
     * @return
     */
    @Override
    public MemberInfoVO getMemberInfo(MemberUser member) {
        member = member.selectById(member.getId());
        MemberInfoVO memberInfoVO = new MemberInfoVO();
        memberInfoVO.setUserId(member.getId());
        memberInfoVO.setUsername(member.getUsername());
        memberInfoVO.setHeadImageUrl(member.getHeadImageUrl());
        memberInfoVO.setNickName(member.getNickName());
        memberInfoVO.setPhone(member.getPhone());
        memberInfoVO.setRoleId(member.getRoleId());
        memberInfoVO.setRoleName(member.getRoleName());
        // TODO 这里还要设置该会员所属的部门
        if(MemberRoleConstant.联企用户.equals(member.getRoleId())) {
            //获取他的部门
            BranchMember branchMember = branchMemberService.getOne(new LambdaQueryWrapper<BranchMember>().eq(BranchMember::getMemberId, member.getId()));
            if(branchMember != null) {
                memberInfoVO.setBranchName(branchMember.getBranchName());
            }
        }
        else if(MemberRoleConstant.企业用户.equals(member.getRoleId())){
            CompanyCore companyCore = companyCoreService.getCompanyByMemberId(member.getId());
            memberInfoVO.setBranchName(companyCore.getCompanyName());
        }
        return memberInfoVO;
    }

    /**
     * 设置会员信息
     * @param member
     * @param setUserDTO
     */
    @Override
    public MemberInfoVO setMemberInfo(MemberUser member, SetUserDTO setUserDTO) {
        if(StrUtil.isNotEmpty(setUserDTO.getNickName())){
            member.setNickName(setUserDTO.getNickName());
        }
        if(StrUtil.isNotEmpty(setUserDTO.getHeadImageUrl())){
            member.setHeadImageUrl(setUserDTO.getHeadImageUrl());
        }
        if(StrUtil.isNotEmpty(setUserDTO.getPhone())){
            member.setPhone(setUserDTO.getPhone());
        }
        this.updateById(member);
        return getMemberInfo(member);
    }

    /**
     * 绑定注册码
     * @param member
     * @param regCode
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long bindRegCode(MemberUser member, String regCode) {
        //注册码必须是手机号格式，避免出错
        //只有企业用户、联企用户、领导账号三种情况，直接通过手机号码，自动识别，这是内置的情况
        CompanyCore companyCore = new CompanyCore();
        companyCore = companyCore.selectOne(new LambdaQueryWrapper<CompanyCore>().eq(CompanyCore::getContactPhone,regCode));
        if(ObjUtil.isNotNull(companyCore)){
            //说明此人是企业人员
            if(ObjUtil.isEmpty(companyCore.getMemberId())){
                companyCore.setMemberId(member.getId());
                companyCore.setMemberName(member.getUsername());
                companyCore.setBindTime(new Date());
                companyCore.setUpdateTime(new Date());
                companyCore.setUpdateBy(member.getUsername());
                companyCore.updateById();
                ///////后续操作 ////////
                //1 更新会员
                member.setRoleId(MemberRoleConstant.企业用户);
                member.setRoleName("企业用户");
                member.updateById();
                return companyCore.getId();
            }
            throw new ServiceException("此企业已经被绑定");
        }
        //如果是企联人员
        BranchMember branchMember = new BranchMember();
        branchMember = branchMember.selectOne(new LambdaQueryWrapper<BranchMember>().eq(BranchMember::getMemberLinkPhone,regCode));
        if(ObjUtil.isNotNull(branchMember)){
            if(ObjUtil.isEmpty(branchMember.getMemberId())){
                branchMember.setMemberId(member.getId());
                branchMember.setMemberLinkName(member.getUsername());
                branchMember.setBindTime(new Date());
                branchMember.updateById();
                ///////后续操作 ////////
                //1 更新会员
                member.setRoleId(MemberRoleConstant.联企用户);
                member.setRoleName("联企用户");
                member.setUsername(branchMember.getMemberLinkName());
                member.updateById();
                //2 更新企联用户企业绑定表
                BranchLink branchLink = new BranchLink();
                List<BranchLink> list = branchLink.selectList(new LambdaQueryWrapper<BranchLink>().eq(BranchLink::getMemberLinkId,branchMember.getId()));
                list.forEach(link->{
                    link.setMemberId(member.getId());
                    link.setMemberName(member.getUsername());
                    link.updateById();
                });
                //3 更新企业诉求对应的一对一人员
                // TODO
                return branchMember.getBranchId();
            }
            throw new ServiceException("此企联人员已经被绑定");
        }
        //如果是领导账号
        LeaderMember leaderMember = new LeaderMember();
        leaderMember = leaderMember.selectOne(new LambdaQueryWrapper<LeaderMember>().eq(LeaderMember::getLeaderPhone,regCode));
        if(ObjUtil.isNotNull(leaderMember)){
            if(ObjUtil.isEmpty(leaderMember.getMemberId())){
                leaderMember.setMemberId(member.getId());
                leaderMember.setLeaderName(member.getUsername());
                leaderMember.setBindTime(new Date());
                leaderMember.updateById();
                //1 更新会员
                member.setRoleId(MemberRoleConstant.领导);
                member.setRoleName("领导");
                member.setUsername(branchMember.getMemberLinkName());
                member.updateById();
                return leaderMember.getId();
            }
            throw new ServiceException("此领导账号已经绑定");
        }
        throw new ServiceException("找不到注册码对应的账号，绑定失败");
    }

    /**
     * 设置部门的联企用户
     * @param setBranchUserDTO
     */
    @Override
    public void setBranchUser(SetBranchUserDTO setBranchUserDTO, LoginUser loginUser) {
        MemberUser memberUser = new MemberUser();
        memberUser = memberUser.selectById(setBranchUserDTO.getMemberId());
        if(ObjUtil.isNotEmpty(memberUser) && MemberRoleConstant.游客.equals(memberUser.getRoleId())){  //只有游客才可以设置
            memberUser.setRoleId(MemberRoleConstant.联企用户);
            memberUser.setRoleName("联企用户");
            memberUser.updateById();
            BranchMember branchMember = new BranchMember();
            SysDept sysDept = sysDeptService.selectDeptById(setBranchUserDTO.getBranchId());
            branchMember = branchMember.selectOne(new LambdaQueryWrapper<BranchMember>().eq(BranchMember::getMemberId,setBranchUserDTO.getMemberId()));
            boolean exist = true;
            if(ObjUtil.isNull(branchMember)){
                branchMember = new BranchMember();
                exist = false;
            }
            branchMember.setMemberLinkName(memberUser.getNickName());
            branchMember.setMemberId(memberUser.getId());
            branchMember.setMemberName(memberUser.getUsername());
            branchMember.setBranchId(setBranchUserDTO.getBranchId());
            branchMember.setBranchName(sysDept.getDeptName());
            branchMember.setMemberLinkPhone(memberUser.getPhone());
            branchMember.setDelFlag(DeleteFlag.NO);
            branchMember.setCreateBy(loginUser.getUsername());
            branchMember.setCreateTime(new Date());
            branchMember.setBindTime(new Date());
            branchMember.setUpdateBy(loginUser.getUsername());
            branchMember.setUpdateTime(new Date());
            branchMember.setDelFlag(DeleteFlag.NO);
            if(exist){
                branchMember.updateById();
            }
            else{
                branchMember.insert();
            }
            return;
        }
        throw new ServiceException("找不到对应的会员或者会员不是游客");
    }

    /**
     * 替换其他类型账号
     * @param replaceUserDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void replaceToOther(ReplaceUserDTO replaceUserDTO) {
        MemberUser origin = this.getById(replaceUserDTO.getMemberId());
        MemberUser target = this.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getPhone,replaceUserDTO.getTargetAccount()));
        if(target!=null && target.getRoleId()==MemberRoleConstant.游客){
            Long originId= origin.getId();
            Long targetId= target.getId();
            origin.setId(targetId);
            target.setId(originId);
            if(replaceUserDTO.getRoleName().equals("企业用户")){
                origin.setRoleId(MemberRoleConstant.游客);
                origin.setRoleName("游客");
                target.setRoleId(101L);
                target.setRoleName("企业用户");
            }
            else if(replaceUserDTO.getRoleName().equals("联企用户")){
                origin.setRoleId(MemberRoleConstant.游客);
                origin.setRoleName("游客");
                target.setRoleId(102L);
                target.setRoleName("联企用户");
            }
            memberUserService.saveOrUpdate(origin);
            memberUserService.saveOrUpdate(target);
            //
            BranchMember branchMember =  branchMemberService.getOne(new LambdaQueryWrapper<BranchMember>().eq(BranchMember::getMemberId,originId));
            if(ObjUtil.isNotNull(branchMember)){
                branchMember.setMemberId(target.getId());
                branchMember.setMemberName(target.getNickName());
                branchMember.setMemberLinkName(target.getUsername());
                branchMember.updateById();
            }
            return;
        }
        throw new ServiceException("找不到对应的目标用户");
    }
}
